import { AxiosError } from 'axios'
import router from '~/router'
import { useMetaTitle } from '~/composables/meta-title'
import { setRouteEmitter } from '~@/utils/route-listener'
import { clearAuthorization, isAuthorizationExpired, useAuthorization } from '~/composables/authorization'

const allowList = ['/login', '/register', '/error', '/401', '/404', '/403']
const loginPath = '/login'

let authClickWatcherInstalled = false
function installAuthExpiryClickWatcher() {
  if (authClickWatcherInstalled)
    return
  authClickWatcherInstalled = true
  document.addEventListener(
    'click',
    () => {
      const token = useAuthorization()
      if (token.value && isAuthorizationExpired(token.value)) {
        clearAuthorization()
        router.push({
          path: loginPath,
          query: { redirect: encodeURIComponent(router.currentRoute.value.fullPath) },
        })
      }
    },
    true,
  )
}

router.beforeEach(async (to, _, next) => {
  setRouteEmitter(to)

  // 获取
  const userStore = useUserStore()
  const token = useAuthorization()

  // token 过期：清空并跳转登录
  if (token.value && isAuthorizationExpired(token.value)) {
    clearAuthorization()
    next({
      path: loginPath,
      query: { redirect: encodeURIComponent(to.fullPath) },
    })
    return
  }

  // 如果是允许的路径，直接通过
  if (allowList.includes(to.path) || to.path.startsWith('/redirect')) {
    next()
    return
  }

  if (!token.value) {
    // 如果没有token，跳转到登录页面
    next({
      path: loginPath,
      query: {
        redirect: encodeURIComponent(to.fullPath),
      },
    })
    return
  }

  // 如果有token但没有用户信息，获取用户信息和路由
  if (!userStore.userInfo) {
    try {
      // 获取用户信息
      await userStore.getUserInfo()
      // 获取路由系统管理的信息
      const currentRoute = await userStore.generateDynamicRoutes()
      router.addRoute(currentRoute)
      next({
        ...to,
        replace: true,
      })
      return
    }
    catch (e) {
      if (e instanceof AxiosError && e?.response?.status === 401) {
        // 跳转到error页面
        next({
          path: '/401',
        })
        return
      }
    }
  }

  // 如果当前是登录页面就跳转到首页
  if (to.path === loginPath) {
    next({
      path: '/dashboard',
    })
    return
  }
  // 不需要对注册页做特殊处理，因为它已经在allowList中

  next()
})

router.afterEach((to) => {
  useMetaTitle(to)

  useLoadingCheck()
  useScrollToTop()
  installAuthExpiryClickWatcher()
})
